'use strict';
module.exports = {
	/**
	 * 该函数的功能是执行用户付费数据回传。
	 * 当用户支付完成后，微信支付会发送支付回调给vk-pay云函数，vk-pay处理完充值金豆或充值会员的逻辑后，调用本函数进行数据回传
	 * 
	 * client/user/pub/callback 前端调用的url参数地址
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			out_trade_no,
			total_fee,
			_add_time,
			_add_time_str
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		_add_time_str = vk.pubfn.timeFormat(_add_time_str, "yyyy-MM-dd hh:mm:ss");
		let douyin_percent = 100; //抖音回传比例，默认全部回传
		// let url = "https://clue.oceanengine.com/outer/wechat/applet/token/1757233229756557"; //巨量资产化小程序回传url
		// let token = "82A9DF19BD811D85ECA0DB54D13DC4A6"; //巨量资产化小程序回传token


		//使用vk公共函数需现在页面顶部引入VK框架，获取今日0点时间戳
		let {
			todayStart
		} = vk.pubfn.getCommonTime(new Date());

		//======获取充值订单信息开始======
		let temp_info = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).get()
		var orderinfo = temp_info.data[0];
		let clickid = temp_info.data[0].clickid || "";

		// if (!clickid || clickid == "NoClickid" || clickid.length < 17) {
		// 	res.tips = "不存在clickid";
		// 	return res;
		// }
		//存在clickid，且该用户的注册时间是今天，则向巨量发送新用户首次付费回传

		console.log("用户注册时间为今天或不存在用户注册时间限制");
		//========抖音回传开始========
		if (orderinfo.tg_pt == "douyin") {

			let orderUser = await db.collection('uni-id-users').where({
				_id: orderinfo.user_id
			}).get();

			// 回传支付事件给巨量
			// 付费回传方式
			let jlurl = "https://ad.toutiao.com/track/activate/?callback=" + clickid +
				"&event_type=2" +
				"&props=%7b%22pay_amount%22%3a" + total_fee + "%7d"
			let tthuichuan_result = await uniCloud.httpclient.request(jlurl, {
				method: 'GET',
				data: {},
				contentType: 'json',
				dataType: 'json'
			})

			if (tthuichuan_result.data.code == 0 || tthuichuan_result.data.status == 200) {
				// 返回被修改的记录条数
				let num = await vk.baseDao.update({
					dbName: "a_recharge", // 表名
					whereJson: { // 条件
						out_trade_no: out_trade_no
					},
					dataJson: { // 需要修改的数据
						is_backhaul: true //订单是否回传
					}
				});
			}

			// 回传记录入库
			let addhc1 = await db.collection('jl_huichuanjilu').add({
				type: "手动回传",
				platform: "douyin",
				user_id: orderinfo.user_id,
				tfid: orderinfo.tfid || "",
				agent_id: orderinfo.invite_code || 0,
				middleman_id: orderinfo.middleman_id || 0,
				adid: orderinfo.ad_id,
				clickid: clickid,
				money: total_fee,
				result: tthuichuan_result.data,
				out_trade_no: out_trade_no,
				time: _add_time,
				time_str: _add_time_str
			})
		}
		//========抖音回传结束========

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}